<template>
	<div style="display: inline-block;">
		<div class="uploadimg" v-if="!justButton">
			<template v-for="(item,$index) in fileList">
				<div class="uploadimgItem" :key="$index" v-if="!!item.base64"
					:style="'width:'+width+'px;height:'+autoHeight+'px;'">
					<el-image :preview-src-list="fileResultShowList" :src="commonUrl(item.base64)" ref="elImage"
						:style="'width:'+(width-2)+'px;height:'+(autoHeight-2)+'px;'">
					</el-image>
				</div>
				<div class="uploadimgClose" @click="handleRemove($index)">
					<i class="el-icon-close"></i>
				</div>
			</template>
			<div class="uploadimgItem" @click="handleClick" v-if="fileList.length<max"
				:style="'width:'+width+'px;height:'+width+'px;'">
				<div class="uploadimgPlus" :style="'width:'+width+'px;top:'+autoTop+'px;'">
					<i class="el-icon-plus"></i>
				</div>
				<input type="file" accept="image/*" :multiple="max>1" ref="input" @change="fileChange"
					class="el-upload__input">
			</div>
		</div>

		<el-button v-if="justButton" icon="el-icon-upload" type="primary" @click="handleClick"
			style="margin-left: 9px;">
			{{title}}
			<input type="file" accept="image/*" :multiple="max>1" ref="input" @change="fileChange"
				class="el-upload__input">
		</el-button>
		<!--浏览图片-->
		<el-button v-if="!justButton&&fileList.length<max" :icon="type=='primary'?'el-icon-view':''" :type="type"
			@click="exploreFile" style="margin-left: 9px;">
			{{sysFileListName}}
		</el-button>
		<el-dialog :visible.sync="visible" :append-to-body="true" :title="sysFileListName" width="99%">
			<SysFileList :visibleChange="visible" :isChoice="true" :isChoiceMany="max>1" :onlyImage="true"
				@choiceFileList="choiceFileList">
			</SysFileList>
		</el-dialog>
	</div>
</template>
<script>
	import fileHelper from '@/common/components/fileHelper.js';
	import common from '@/common/common.js';
	import SysFileList from "@/System/SysFileList";

	export default {
		name: "uploadimg",
		components: {
			SysFileList
		},
		mixins: [common.baseVM],
		props: {
			max: {
				type: Number,
				default: 1
			},
			disabled: {
				type: Boolean,
				default: false
			},
			value: {
				type: String | Array
			},
			title: {
				type: String,
				default: '上传图片'
			},
			justButton: {
				type: Boolean,
				default: false
			},

			sysFileList: {
				type: Boolean,
				default: true
			},
			sysFileListName: {
				type: String,
				default: '浏览图片'
			},

			width: {
				type: Number,
				default: 100
			},
			height: {
				type: Number,
				default: 0
			},
			type: {
				type: String,
				default: "primary"
			}
		},
		computed: {
			fileResultShowList() {
				var arr = [];
				for (var i = 0; i < this.fileList.length; i++) {
					arr.push(this.commonUrl(this.fileList[i].base64));
				}
				return arr;
			},
			fileResultList() {
				var arr = [];
				for (var i = 0; i < this.fileList.length; i++) {
					arr.push(this.fileList[i].base64);
				}
				return arr;
			},
			autoHeight() {
				if (this.height <= 0) {
					return this.width;
				}
				return this.height;
			},
			autoTop() {
				//100对应的是30
				if (this.width <= 40) {
					var r2 = parseInt(30 / 100 * this.width) - 7;
					return r2;
				}
				var r = parseInt(30 / 100 * this.width) - 3;
				return r;
			}
		},
		watch: {
			value(n, old) { //外面的v-model值变化的时候,触发init方法
				// console.log("watch.value 外面的v-model值变化的时候,触发init方法");
				// console.log("watch.value old,new:", old, n);
				//影响自动上传图片
				this.initFile(n, false);
			},
			fileList(n, old) {
				//this.$emit("change", n);
			}
		},
		data() {
			return {
				fileList: [],
				visible: false
			};
		},
		methods: {
			initFile(n, isAll) {
				// console.log(n, isAll);
				if (n == null || n == "") {
					this.fileList = [];
					return;
				}
				var initFileList = () => {
					if (typeof n == "string") {
						this.fileList = [{
							fileName: fileHelper.getFileName(n),
							base64: n
						}];
						return;
					}
					var forMax = n.length > this.max ? this.max : n.length;
					var arr = [];
					for (var i = 0; i < forMax; i++) {
						var item = n[i];
						if (typeof(item) == "string") {
							arr.push({
								fileName: fileHelper.getFileName(item),
								base64: item
							});
						} else {
							arr.push(n);
						}
					}
					this.fileList = arr;
				};

				if (this.fileList == null || this.fileList.length == 0) {
					initFileList();
				}
				if (!isAll) return; //不是全部更新,就不管
				initFileList();
			},
			setFileList(arr) {
				var r = [];
				if (arr instanceof Array) {
					for (var i = 0; i < arr.length; i++) {
						var item = arr[i];
						r.push({
							fileName: this.getTheFileName(item),
							base64: item
						});
					}
				} else {
					r.push({
						fileName: this.getTheFileName(arr),
						base64: arr
					});
				}
				this.fileList = r;
			},
			choiceFileList(arr) {
				if (arr == null || arr.length == 0) return;
				var isArr = this.max > 1;
				if (isArr) {
					for (var i = 0; i < arr.length; i++) {
						var item = arr[i];
						this.fileList.push({
							fileName: item.fileName,
							base64: item.base64
						});
					}
				} else {
					this.fileList = [];
					var item = arr[0];
					this.fileList.push({
						fileName: item.fileName,
						base64: item.base64
					});
				}
				this.visible = false;
				this.setValue();
			},
			getTheFileName(item) {
				if (!item) return '';
				var index = item.lastIndexOf('/');
				if (index == -1) return fileHelper.getFileName(item);
				var r = item.substr(index + 1);
				return r;
			},
			setValue() {
				this.$emit("change", this.fileList);
				if (this.justButton) {
					this.fileList = [];
					return;
				}
				//console.log("setValue", this.fileResultList);
				if (this.max == 1) {
					this.$emit("input", this.fileResultList[0]);
					return;
				}
				this.$emit("input", this.fileResultList);
			},
			handleClick() {
				if (!this.disabled) {
					this.$refs.input.value = null;
					this.$refs.input.click();
				}
			},
			//上传图片
			fileChange(event) {
				//console.log(event);
				//console.log(event.target.files);
				// return;
				if (event.target.files.length == 0 || !event.target.files[0].size) return; //判断是否有文件数量
				var files = []; //重新弄个数组做为参数,是因为原来的数组不支持.map
				for (var i = 0; i < event.target.files.length; i++) {
					files.push(event.target.files[i]);
				}
				//console.log("files", files);
				this.addFileList(files); //获取files文件组传入处理
				event.target.value = '' //清空val值，以便可以重复添加一张图片
			},
			addFileList(files) {
				var total = this.fileList.length + files.length;
				if (this.max != 1) { //只有一个的情况,覆盖掉
					if (total > this.max) {
						var tempFiles = [];
						var hasCount = this.max - this.fileList.length;
						for (var i = 0; i < hasCount; i++) {
							tempFiles.push(files[i]);
						}
						files = tempFiles;
					}
				}
				fileHelper.convertBase64((data) => {
					//转换成功
					//console.log(data);
					if (this.max == 1) this.fileList = [];
					for (var i = 0; i < data.length; i++) {
						this.fileList.push(data[i]);
					}
					this.setValue();

					//自动上传图片
					if (this.sysFileList) {
						this.uploadImages(data);
					}
				}, files);
			},
			handleRemove($index) {
				this.fileList.splice($index, 1);
				this.setValue();
			},

			uploadImages(imgList) {
				//console.log(imgList);
				Promise.all(
					imgList.map((item) => {
						return this.uploadImage(item);
					})
				).then((data) => {
					this.setValue();
					this.showToast("图片上传:" + this.comLan.js.opSuccess, "success");
				}).catch(e => {
					//this.showToast(this.comLan.js.opFail + ":" + e, "error");
				});
			},
			uploadImage(item) {
				//console.log(item)
				return new Promise((resolve, reject) => {
					this.post("api/System/SysFileAdd", {
						SysFileName: item.fileName,
						FilePath: item.base64
					}).then(data => {
						var filePath = this.commonUrl(data.Result.FilePath);
						item.base64 = filePath;
						resolve(data);
					}).catch(e => {
						reject(e);
					});
				});
			},
			exploreFile() {
				this.visible = true;
			}
		},
		created() {
			// console.log("created", this.value);
			this.initFile(this.value, true);
		}
	};
</script>
<style>
	.uploadimgClose {
		width: 14px;
		height: 14px;
		line-height: 14px;
		border-radius: 50%;
		background: #7536D0;
		color: #fff !important;
		font-weight: 600;
		justify-content: center !important;
		font-size: 14px;
		align-items: center;
		cursor: pointer;
		display: inline-block;

		position: relative;
		left: -8px;
		top: -16px;
	}

	.uploadimgPlus {
		font-size: 21px;
		line-height: 28px;
		color: #8c939d;
		text-align: center;
		cursor: pointer;

		width: 100px;
		position: relative;
		top: 30px;
	}

	.uploadimg {
		margin: 0;
		display: inline-block;
		vertical-align: middle;
	}

	.uploadimg .el-image {
		overflow: inherit !important;
		display: block !important;
	}

	.uploadimgItem {
		background-color: #fff;
		border: 1px solid #c0ccda;
		border-radius: 6px;
		box-sizing: border-box;
		width: 100px;
		height: 100px;
		margin-right: 0px;
		/* margin-left: -5px; */
		display: inline-block;
		margin-bottom: 5px;
	}
</style>
